import 'package:flutter/material.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/model/extensionModel.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicTool.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/page/user/appointmentTime.dart';
import 'package:gd_assistant/page/user/selectArchivesPage.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/eventBus.dart';
import 'package:gd_assistant/util/publicUtil.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:gd_assistant/page/user/healthRecordPage.dart';

class appointmentInfoPage extends StatefulWidget {
  appointmentInfoPage({Key key, 
                      this.exten,
                      this.userName,
                      this.age,
                      this.sex,
                      this.userid,
                      this.packageOrderId = '',
                      this.callBack}) : super(key : key);
  Extension exten;
  String userName = '';
  String age = '';
  String sex = '';
  String userid = '';
  String packageOrderId;
  Function callBack;
  @override
  _appointmentInfoState createState() => _appointmentInfoState();
}

class _appointmentInfoState extends State<appointmentInfoPage> {
  bool isDark = false;
  bool isEdit = true;
  String name = "";
  String sex = "";
  String age = "";
  String status = "";  //未就诊:200，已就诊:400，已取消:300
  String appointTime = "";
  String appointAddress = "";
  List<String> appointTags = [];
  TextEditingController appointInfo = TextEditingController();
  List<String> imgs = [];
  //孕期显示
  String pregnancyShow = "";

  //上传的图片数组
  List<String> urlImages = [];
  List<String> uploadImages = [];
  bool isLoad = false;

  //上传图片
  uploadImage() async {
    List<String> result = await publicUtil.onUploadFiles(uploadImages);
    imgs = [];
    imgs.addAll(urlImages.map((v)=>v.substring(GlobalConfig.qiNiuUri.length)).toList());
    imgs.addAll(result);
    await updateAppointment();
  }
  
  //获取状态值
  getStatus(String status) {
    switch (status) {
      case "未就诊":
        return 200.toString();
        break;
      case "已就诊":
        return 400.toString();
        break;
      case "已取消":
        return 300.toString();
        break;
      default:
    }
  }
  //提交预约
  updateAppointment() async {
    dynamic cb;
    if (widget.exten == null) {
      //新增
      cb = await apiHandler.createAppointment(widget.userid, widget.packageOrderId, RelativeDateFormat.timeStampFormat(appointTime), appointTags, appointAddress, appointInfo.text, imgs);
    }else{  
      //修改
      cb = await apiHandler.updateAppointment(widget.exten.order.orderId, RelativeDateFormat.timeStampFormat(appointTime), appointTags, appointAddress, appointInfo.text, getStatus(status), imgs);
    }
    TostUtil.removeLoading(context);
    if (cb != null) {
      TostUtil.show("提交预约成功");
      Navigator.pop(context);
      if (widget.callBack != null) {
        widget.callBack();
      }
    }
  }

  final bottomTitles = ["未就诊","已就诊","已取消"];
  _bottomTap(title) {
    setState(() {
      status = title;
    });
  }

  @override
  void initState() {
    super.initState();
    EventBus().on("timeAndAddressChange", (parmas){
      setState(() {
         appointAddress = parmas["address"];
         appointTime = parmas["time"];
      });
    });
    if (widget.exten != null) {
      _loadData();
    } else {
      name = widget.userName;
      sex = widget.age;
      age = widget.sex;
    }
  }

  _loadData() async {
    isLoad = true;
    Extension exten = await apiHandler.getAppointmentInfo(widget.exten.order.orderId);
    isLoad = false;
      name = exten.user.name;
      sex = exten.user.sex;
      age = exten.user.age;
      switch (exten.order.status) {
        case 200:
          status = "未就诊";
          isEdit = true;
          break;
        case 400:
          status = "已就诊";
          isEdit = false;
        break;
        case 300:
          status = "已取消";
          isEdit = false;
        break;
        default:
      }
      appointTime = exten.order.workTime != 0 ? RelativeDateFormat.YMDHMformat(exten.order.workTime) : "";
      appointAddress = exten.order.address;
      appointTags = exten.order.items;
      appointInfo.text = exten.order.instructions != null ? exten.order.instructions : "";
      imgs = exten.order.checklistImgs.map((img)=>GlobalConfig.qiNiuUri + img).toList();
      urlImages = imgs;
      if (exten.order.babyBirth > 0) {
        pregnancyShow = "\n (已生产)";
      } else if (exten.order.expectedDate > 0) {
        pregnancyShow = "\n" + RelativeDateFormat.pregnancyFormat(exten.order.expectedDate - 40*7 * 24 * 60 * 60 * 1000, exten.order.workTime);
      } else if (exten.order.lastMenstruation > 0) {
        pregnancyShow = "\n" + RelativeDateFormat.pregnancyFormat(exten.order.lastMenstruation, exten.order.workTime);
      }
      setState(() {});
  }

  _statusColor(){
    switch (status) {
      case "已取消":
         return Colors.grey;
        break;
      case "已就诊":
         return Colors.red;
        break;
      case "未就诊":
         return Colors.blue; 
        break;
      default:
    }
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off("timeAndAddressChange");
    appointInfo.dispose();
  }

  _getContentWidget() {
    if (isLoad) {
      return loadingWiget();
    }
    final EdgeInsets padding = MediaQuery.of(context).padding;
    return Container(
        color: isDark ? Colours.dark_bg_gray : Colors.white,
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView(
                children: <Widget>[
                  ZLSelectField(
                    title: name,
                    pliceHorder: "(${sex}，${age})",
                  ),
                  Offstage(
                    offstage: status.length == 0,
                    child: ZLSelectField(
                      title: "预约状态",
                      text: status,
                      onTap: () {
                        publicTool.showBottomSheet(context, bottomTitles, _bottomTap);
                      },
                      isEdit: isEdit,
                      color: _statusColor(),
                    ),
                  ),
                  ZLSelectField(
                    title: "预约时间",
                    text: appointTime + pregnancyShow,
                    pliceHorder: "请选择预约时间",
                    onTap: () {
                      Navigator.of(context).push(
                        CustomRoute(appointmentTimePage(packageOrderId: widget.packageOrderId.length == 0 ? widget.exten.order.servicePackageOrderId : widget.packageOrderId))
                      ); 
                    },
                    isEdit: isEdit,
                  ),
                  ZLSelectField(
                    title: "预约地点",
                    text: appointAddress
                  ),
                  ZLSelectField(
                    title: "预约项目",
                    pliceHorder: appointTags.length > 0 ? "" : "请选择预约项目",
                    onTap: () {
                      //点击去预约项目
                      Navigator.of(context).push(
                        CustomRoute(selectArchivesPage(selectTags: appointTags, selectedEnd: (tags){
                          setState(() {
                            appointTags = tags;
                          });
                        },))
                      ); 
                    },
                    isEdit: isEdit,
                  ),
                  ZLTagsView(
                    titles: appointTags,
                  ),
                  Offstage(
                    offstage: appointInfo.text.length == 0 && isEdit == false,
                    child: ZLTextView(
                      title: "预约详情",
                      controller: appointInfo,
                      pliceHorder: "请输入",
                      isEdit: isEdit,
                    ),
                  ),
                  Offstage(
                    offstage: imgs.length == 0 && isEdit == false,
                    child: ZLImageSelectView(
                      title: "上传资料和图片",
                      isEdit: isEdit,
                      images: imgs,
                      onChange: (urlPaths, listImagePaths){
                        print(urlPaths);
                        print(listImagePaths);
                        urlImages = urlPaths;
                        List<String> up = [];
                        for (Media path in listImagePaths) {
                          up.add(path.path);
                        }
                        uploadImages = up;
                      },
                    ),
                  )
                ],
              ),
            ),
           Offstage(
             offstage: !isEdit,
             child: Container(
              padding: EdgeInsets.only(bottom: padding.bottom),
              width: double.infinity,
              height: 65 + padding.bottom,
              color: isDark ? Colours.dark_bg_color : Colors.white,
              child: ZLButton(
                  title: "提交",
                  onTap: appointTime != "" && appointAddress != "" && appointTags.length > 0 ? (){
                    TostUtil.showLoading(context, "预约信息提交中...");
                    uploadImage();
                  } : null
                )
            ),
           )
          ],
        )
      );
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.exten == null?"预约":"预约详情"),
        elevation: 0,
        actions: <Widget>[
          Offstage(
            child: new IconButton(
              icon: new Icon(Icons.archive),
              onPressed: () {
                //跳转到健康档案
                Navigator.of(context).push(
                  CustomRoute(healthRecordPage(userid: widget.exten.user.sid == null ? widget.userid : widget.exten.user.sid, orderid: widget.exten.order.servicePackageOrderId, userName: widget.exten.user.name, isExpire: false))
                );  
              }
            ),
            offstage: widget.exten == null,
          )
        ],
      ),
      body:_getContentWidget()
    );
  }
}